<script lang="ts">
import Vue from 'vue'
import NavBar from "@/components/nav-bar/nav-bar.vue";
import my_print_pay from "@/components/PayCard/PayCard.vue";
import {editImageChange, myReplace} from "@/utils/utils";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import tips from "@/utils/tips";
import {uploadImageServer} from "@/services/office";

let overSizedFiles = []
export default Vue.extend({
  name: "print_photo",
  components: {my_upload_card, uploadSelectPopup, NavBar, my_print_pay},
  data() {
    return {
      showUploadPopup: false,
      imageUrls: [], // 照片列表
      currentImage: 0, // 轮播图当前图片索引
      serverImageUrls: [], // 服务器使用的文件路径

      currentImageUrl: '', // 编译照片路径
      localImageUrls: [], // 服务器使用的文件路径
      overSizedFilesIndex: [], // 上传不了文件index

      selectedIndex: 0, // ....
    }
  },
  computed: {
    lang(): any {
      return this.$t('print_photo');
    }
  },
  methods: {
    // 上传照片
    onAddPhoto() {
      this.showUploadPopup = true;
    },

    // 微信里上传
    chooseMessage() {
      uni.chooseMessageFile({
        count: 9,
        type: 'image',
        success: (res) => {
          const validFiles = this.checkFileSizes(res.tempFiles);
          // 过滤完后的照片
          if (validFiles.length >= 1) {
            this.servicesUploadImage(validFiles, 'path');
          }
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index: number) {
      const sourceTypes: Array<any> = ['camera', 'album'];
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'], // 照片压缩或原图
        success: (res) => {
          console.log("chooseMedia-=-=", res)
          const validFiles = this.checkFileSizes(res.tempFiles);
          if (validFiles.length >= 1) {
            this.servicesUploadImage(validFiles, 'tempFilePath')
          }
        },
      });
    },
    // 检查格式
    checkFileSizes(files: any[]) {
      const MAX_FILE_SIZE = (20 * 1024 * 1024); // 2MB
      const overSizedFilesIndex = [];
      const validFiles = [];

      files.forEach((file, index) => {
        // console.log(`处理文件: ${file.name}, 大小: ${file.size}, models:${models}`); // 调试信息
        if (file.size > MAX_FILE_SIZE) {
          overSizedFilesIndex.push(index + 1);
        } else {
          validFiles.push(file);
        }
      });

      if (overSizedFilesIndex.length >= 1) {
        console.log("this.lang.file_size_limit", myReplace(this.lang.file_size_limit, '{index}', overSizedFiles))
        // this.lang.file_size_limit.replace('{index}', overSizedFiles)
        tips.toast(myReplace(this.lang.file_size_limit, '{index}', overSizedFilesIndex), 3000)
      }

      overSizedFiles = overSizedFilesIndex
      return validFiles;
    },
    // 服务器上传文件 获取文件路径
    servicesUploadImage(list: any, path: string) {
      // 显示加载提示
      uni.showLoading({title: '加载中...'});

      const promises = list.map((item: any) =>
          new Promise((resolve, reject) => {
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: item[path],
              success: (res) => {
                const resData = JSON.parse(res.data);
                if (resData.code === 200) {
                  console.log("Upload success:", resData.data);
                  resolve({...resData.data, localPath: item[path]});
                } else {
                  reject(new Error(`Upload failed with code: ${resData.code}`));
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
                reject(err);
              }
            });
          })
      );

      // 等待所有上传完成
      Promise.all(promises).then((results) => {
        console.log('Upload results:', results);
        // 更新图片列表 添加的前面增加
        this.imageUrls = [...results.map(item => item.url), ...this.imageUrls];
        this.serverImageUrls = [...results.map(item => item.file_path), ...this.serverImageUrls];
        this.localImageUrls = [...results.map(item => item.localPath), ...this.localImageUrls];
        uni.hideLoading(); // 隐藏加载提示

        if (overSizedFiles.length >= 1) {
          console.log("this.lang.file_size_limit", myReplace(this.lang.file_size_limit, '{index}', overSizedFiles))
          // this.lang.file_size_limit.replace('{index}', overSizedFiles)
          tips.toast(myReplace(this.lang.file_size_limit, '{index}', overSizedFiles))
        }

        console.log('Updated this.imageUrls:', this.imageUrls);
        console.log('Updated this.serverImageUrls:', this.serverImageUrls);
        console.log('Updated this.localImageUrls:', this.localImageUrls);
      }).catch((error) => {
        console.error('上传过程中发生错误:', error);
        uni.hideLoading(); // 隐藏加载提示
      });
    },
    // 删除照片
    closeImage(index: any) {
      console.log('===============closeDrive', index)
      this.imageUrls.splice(index, 1)
      this.serverImageUrls.splice(index, 1)
      this.localImageUrls.splice(index, 1)
    },


    // 编译照片
    async onEditImage() {
      const index = this.currentImage;
      const currentImage: any = await editImageChange(this.localImageUrls[index]);
      console.log("currentImage", currentImage);

      uni.showLoading({title: '加载中...'})
      uni.uploadFile({
        url: uploadImageServer,
        name: 'file',
        filePath: currentImage,
        formData: {is_black_white: 'false'},
        success: (res) => {
          console.log(res)
          const resData = JSON.parse(res.data);
          if (resData.code === 200) {
            // 更新图片列表
            console.log("Upload success-=--=-=-=-=-=:", resData.data);
            const {url, file_path} = resData.data;
            // 为了确保更新响应式
            this.$set(this.imageUrls, index, url);
            this.$set(this.serverImageUrls, index, file_path);
            this.$set(this.localImageUrls, index, currentImage);
            uni.hideLoading()
            console.log('Updated this.imageUrls:', this.imageUrls);
            console.log('Updated this.serverImageUrls:', this.serverImageUrls);
            console.log('Updated this.localImageUrls:', this.localImageUrls);
          } else {
            console.error(`Upload failed with code: ${resData.code}`);
          }
        },
        fail: (err) => {
          console.log('locale upload fail', err);
        }
      });
    },

    // 轮播图刷新
    onSwiperChange(event: any) {
      this.currentImage = event.detail.current; // 获取当前索引
    },

    // 点击打印
    onPrint() {
      uni.navigateTo({
        url: `/pages/photo_pay/photo_pay?type=2&image=` + encodeURIComponent(JSON.stringify(this.imageUrls))
      })
    }
  },
})
</script>

<template>
  <view>
    <nav-bar :page-title="lang.page_name"/>
    <view :class="locale">
      <view class="center text-36" style="padding: 40rpx 0 40rpx 0">
        <view v-if="imageUrls.length > 0" style="text-align: center" @click="onEditImage">{{ lang.picture_edit }}</view>
      </view>

      <swiper class="photo-card-box" @change="onSwiperChange">
        <!--   还没上传-->
        <swiper-item v-if="imageUrls.length <= 0">
          <view class="card-box" @click="onAddPhoto">
            <view class="flex-center text-28 gap-20 radio-20 center add-photo" hover-class="hover">
              <u-icon name="plus" color="#2BE2A0" size="18"/>
              <view>{{ lang.add_image }}</view>
            </view>
            <!--            <u-icon  name="plus-circle-fill" color="#07C160" size="52"></u-icon>-->
            <!--            <image class="radio-20 photo" src="/static/icon/home/print_image.jpg"/>-->
          </view>
        </swiper-item>

        <swiper-item v-if="imageUrls.length > 0" v-for="(item, index) in imageUrls" :key="index">
          <view class="card-box">
            <view class="close-icon" @click="closeImage(index)">
              <u-icon size="26px" color="#0009" name="close-circle-fill"/>
            </view>
            <view class="photo-box" @click="onEditImage">
              <image class="radio-20 photo" :src="item" mode="aspectFit"/>
            </view>
          </view>
        </swiper-item>
      </swiper>

      <view v-if="imageUrls.length > 0" class="margin-top-40 center text-32">
        <view class="radio-20 bg-white ltr number">
          {{ `${currentImage + 1} / ${imageUrls.length}` }}
        </view>
      </view>

      <!--    最下面-->
      <view v-if="imageUrls.length >0" class="bg-white print-card-box zh-CN ltr">
        <view class="flex-around padding-20 gap-30">

          <view :class="['flex-center text-28 gap-20 radio-20 center add-photo', locale]" hover-class="hover"
                @click="onAddPhoto">
            <u-icon name="plus" color="#2BE2A0" size="18"/>
            <view>{{ lang.add_image }}</view>
          </view>
          <view class="flex-center text-28 radio-20 center print" hover-class="hover" @click="onPrint">
            {{ otherLang.print }}
          </view>
        </view>
      </view>

      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<style scoped lang="scss">
.photo-card-box {
  height: 900rpx;

  .card-box {
    margin: 0 40rpx 0 40rpx;
    position: relative;
    background: white;
    height: 898rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    border-radius: 4rpx;
  }

  .close-icon {
    position: absolute;
    top: -5rpx;
    right: -5rpx;
  }

  .photo-box {
    width: 100%;
    height: 100%;
  }

  .photo {
    width: 100%;
    height: 100%;
  }
}

.number {
  padding: 10rpx 14rpx 10rpx 14rpx;
}

.photo-change-box {
  width: 140rpx;
  position: relative;

  .photo {
    width: 140rpx;
    height: 140rpx;
  }

  .text-box {
    padding: 2px 7px;
    text-align: center;
    border-radius: 14rpx;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    color: white;
    background: rgba(0, 0, 0, 0.40);
  }

  .selective {
    background: var(--brand-color, #0186FF);
  }
}


.print-card-box {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
}


.print {
  height: 88rpx;
  width: 40%;
  color: white;
  background: linear-gradient(127deg, #2BE2A0 -13.26%, #12C287 105.04%), #07C160;
}

.add-photo {
  height: 88rpx;
  width: 40%;
  color: #2BE2A0;
  border: 1px solid #2BE2A0;
}
</style>